package com.kqb.sgadmin.manager.captcha;

import com.aliyun.captcha20230305.Client;
import com.aliyun.captcha20230305.models.*;
import com.kqb.sgadmin.config.properties.CaptchaProperties;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author 杉果树皮
 */
@Component
@Slf4j
public class CaptchaManager {


    @Resource
    private Client captchaClient;

    @Resource
    private CaptchaProperties captchaProperties;

    public Boolean verify(String captchaVerifyParam) {

        VerifyIntelligentCaptchaRequest verifyIntelligentCaptchaRequest = new VerifyIntelligentCaptchaRequest()
                .setCaptchaVerifyParam(captchaVerifyParam)
                .setSceneId(captchaProperties.getSceneId());

        VerifyIntelligentCaptchaResponse verifyIntelligentCaptchaResponse = null;
        try {
            verifyIntelligentCaptchaResponse = captchaClient.verifyIntelligentCaptcha(verifyIntelligentCaptchaRequest);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return handleResponse(verifyIntelligentCaptchaResponse);
    }

    private Boolean handleResponse(VerifyIntelligentCaptchaResponse verifyIntelligentCaptchaResponse) {
        if (verifyIntelligentCaptchaResponse == null || verifyIntelligentCaptchaResponse.getBody() == null) {
            log.warn("验证响应体为空");
            return false;
        }
        VerifyIntelligentCaptchaResponseBody.VerifyIntelligentCaptchaResponseBodyResult result = verifyIntelligentCaptchaResponse.getBody().getResult();
        if (result != null) {
            return result.getVerifyResult();
        }
        return false;
    }

}
